package com.czxy.zuul;

import com.czxy.config.JwtProperties;
import com.czxy.config.PathProperties;
import com.czxy.util.JwtUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 张青卯
 */
@Component
public class AuthFilter extends ZuulFilter {

    private final JwtProperties jwtProperties;

    private final PathProperties pathProperties;

    @Autowired
    public AuthFilter(JwtProperties jwtProperties,PathProperties pathProperties){
        this.jwtProperties = jwtProperties;
        this.pathProperties = pathProperties;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        StringBuffer url = request.getRequestURL();
        return isAllowPath(url);
    }

    private Boolean isAllowPath(StringBuffer url){
        boolean flag = true;
        List<String> list = pathProperties.getAllowPaths();
        for (String path : list) {
            if (url.indexOf(path)!=-1) {
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("authorization");
        if (token != null){
            try {
                JwtUtils.getInfoFromToken(token,jwtProperties.getPublickey());
                context.addZuulRequestHeader("authorization",token);
                return null;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        context.setSendZuulResponse(false);
        context.setResponseStatusCode(401);
        return null;
    }
}
